<template>
  <el-select
    v-if="editMode"
    class="simple-select"
    ref="dummySelectRef"
    v-bind="$attrs"
    clearable
    @visible-change="visibleChange"
    @clear="handleClear"
    v-loading="dummyInitializing"
    element-loading-custom-class="small-loading-icon"
  >
    <el-option
      v-for="item in dummyList"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
  <div
    v-else
    class="simple-text"
    :style="`justify-content: ${textAlign}`"
    v-loading="dummyInitializing"
    element-loading-custom-class="small-loading-icon"
  >
    {{ selectRow ? selectRow.nickname : '' }}
    <el-link
      v-if="$attrs.modelValue && showCopy"
      class="copy-link"
      :underline="false"
      @click="copyText(selectRow ? selectRow.nickname : '')"
    >
      <el-icon>
        <DocumentCopy />
      </el-icon>
      <span class="text">{{ t('common.clickCopy') }}</span>
    </el-link>
  </div>
  <Dialog v-model="dialogVisible" :title="t('systemUser.select.title')" width="1000">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item :label="t('systemUser.fields.nickname')" prop="nickname">
          <el-input
            v-model="queryParams.nickname"
            :placeholder="t('common.inputTextPlaceholder') + t('systemUser.fields.nickname')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item :label="t('systemUser.fields.mobile')" prop="mobile">
          <el-input
            v-model="queryParams.mobile"
            :placeholder="t('common.inputTextPlaceholder') + t('systemUser.fields.mobile')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px" />
            {{ t('common.search') }}
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" />
            {{ t('common.reset') }}
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <vxe-table
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :row-config="{ keyField: 'id' }"
      :radio-config="{ reserve: true, strict: false }"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
      @radio-change="radioChangeEvent"
    >
      <vxe-column type="radio" width="60" align="center" />
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('systemUser.fields.nickname')"
        field="nickname"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('systemUser.fields.jobCode')"
        field="jobCode"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('systemUser.fields.deptName')"
        field="deptName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('login.mobileNumber')"
        field="mobile"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <template #footer>
      <el-button @click="handleSelect" type="primary" :disabled="!selectRow"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { useAttrs } from 'vue'
import { ElSelect } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/store/modules/app'
import { VxeTableInstance, VxeTableEvents } from 'vxe-table'
import { DocumentCopy } from '@element-plus/icons-vue'
import { useClipboard } from '@vueuse/core'
import * as UserApi from '@/api/system/user'
import { getUserInApp, UserPageRespVO } from '@/api/system/user'

const props = defineProps({
  showCopy: {
    type: Boolean,
    default: true
  },
  textAlign: {
    type: String,
    default: 'flex-start'
  }
})

const attrs = useAttrs()
const { t } = useI18n()
const { copy } = useClipboard()
const message = useMessage()

const copyText = async (text: string) => {
  try {
    await copy(text)
    message.success(t('common.copySuccess'))
  } catch (e) {
    message.error(t('common.copyError'))
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

const editMode = inject('editMode', true)

const dialogVisible = ref(false)

const loading = ref(false)
const dummyInitializing = ref(false)

const list = ref<UserPageRespVO[]>([])
const total = ref(0)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  nickname: undefined,
  mobile: undefined
})
const queryFormRef = ref() // 搜索的表单

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const open = async () => {
  dialogVisible.value = true
  await nextTick()
  if (selectRow.value) {
    setSelectRow(selectRow.value)
  }
  await getList()
}

const dummySelectRef = ref<ElSelect | null>(null)
const dummyList = ref([])
const visibleChange = (visible: boolean) => {
  if (visible) {
    dummySelectRef.value?.blur()
    open()
  }
}

const tableRef = ref<VxeTableInstance<UserPageRespVO>>()
const selectRow = ref<UserPageRespVO>()

const radioChangeEvent: VxeTableEvents.CurrentChange<UserPageRespVO> = ({ newValue }) => {
  if (newValue) {
    selectRow.value = newValue
  } else {
    selectRow.value = undefined
  }
}

const setSelectRow = (row: UserPageRespVO | undefined) => {
  selectRow.value = row
  const $table = tableRef.value
  if ($table) {
    $table.setRadioRow(row)
  }
}

const emits = defineEmits(['selected', 'update:modelValue'])

const handleSelect = () => {
  emits('update:modelValue', selectRow.value?.id)
  emits('selected', selectRow.value)
  dialogVisible.value = false
}

const handleClear = () => {
  emits('update:modelValue', undefined)
  emits('selected', undefined)
  setSelectRow(undefined)
}

const initDummyOption = (data: UserPageRespVO) => {
  dummyList.value = [{ value: data.id, label: data.nickname }]
}

watchEffect(async () => {
  // 监控ID变化 查询数据用来回显
  if (attrs.modelValue) {
    try {
      dummyInitializing.value = true
      // 查询数据
      const data = await UserApi.getUserInApp(attrs.modelValue as number)
      if (data) {
        // 尝试设置选中行 此时对话框可能并没有弹出 但是没关系 会将选中行记录下来 等对话框弹出时再设置选中行
        setSelectRow(data)
        initDummyOption(data)
      }
    } finally {
      dummyInitializing.value = false
    }
  }
})
</script>

<style scoped lang="scss">
.simple-select {
  :deep(.el-select__wrapper) {
    border-radius: 0 !important;
    box-shadow: none !important;
    padding: 0 !important;
    border-bottom: 1px solid var(--el-border-color);
  }
}

.simple-text {
  display: flex;
  align-items: center;

  .copy-link {
    visibility: hidden;
    margin-left: 6px;

    .text {
      font-size: 12px;
      visibility: hidden;
    }

    &:hover {
      .text {
        visibility: visible;
      }
    }
  }

  &:hover {
    .copy-link {
      visibility: visible;
    }
  }
}
</style>
